<template>
    <Card>
        <div class="contract-detial-btns top-btn">
            <Button type="primary" @click="back">返回</Button>
            <template v-if="!isReadOnly">
                <template v-if="isApprove">
                    <Button type="primary" @click="approve('pass')">审核通过</Button>
                    <Button type="primary" @click="approve('reject')">拒绝</Button>
                </template>
                <template v-else-if="!isApproved">
                    <Button type="primary" @click="save">保存</Button>
                    <Button type="primary" @click="submit">提交</Button>
                    <Button type="primary" @click="printFile">模板生成</Button>
                    <Button type="primary" @click="setSmallprogram">生成二维码</Button>
                </template>
            </template>
        </div>
        <!--        <div>-->
        <!--            <div class="contract-detial-btns" v-if="isApprove">-->
        <!--                <Button type="primary" @click="back">返回</Button>-->
        <!--                <template v-if="!isReadOnly || isApproved">-->
        <!--                    <Button type="primary" @click="approve('pass')">审核通过</Button>-->
        <!--                    <Button type="primary" @click="approve('return')">退件</Button>-->
        <!--                    <Button type="primary" @click="approve('reject')">拒绝</Button>-->
        <!--                </template>-->
        <!--            </div>-->
        <!--            <div class="contract-detial-btns" v-else>-->
        <!--                <Button type="primary" @click="back">返回</Button>-->
        <!--                <template v-if="!isReadOnly">-->
        <!--                    <Button type="primary" @click="save">保存</Button>-->
        <!--                    <Button type="primary" @click="submit">提交</Button>-->
        <!--                    <Button type="primary" @click="printFile">模板生成</Button>-->
        <!--                </template>-->
        <!--            </div>-->
        <!--        </div>-->
        <div class="contract-detail-collapse">
        <Collapse v-model="openPanel">
            <Panel name="1" v-if="(isApprove || isApproved || this.pageParams.processStatus === 'refuse' )|| this.pageParams.processStatus==='approved'">
                日志
                <div class="content" slot="content">
                    <approveHistory :Obj="Obj"/>
                </div>
            </Panel>
            <Panel name="2">
                基本信息
                <div class="content" slot="content">
                    <BaseInfo ref="baseInfo" :formData="pageInfo"/>
                </div>
            </Panel>
            <Panel name="3">
                合同信息
                <div class="content" slot="content">
                    <contractInfo :Obj="Obj" />
                </div>
            </Panel>
            <Panel name="4">
                金融产品
                <div class="content" slot="content">
                    <FinanceInfo :Obj="Obj"/>
                </div>
            </Panel>
            <Panel name="5">
                业务办理
                <div class="content" slot="content">
                    <Business
                        ref="business"
                        :Obj="Obj"
                        :pageParams="pageInfo"
                        :dataDict="dataDict"
                        :isApprove="isApprove"
                        :isApproved="isApproved"
                        :isReadOnly="isReadOnly"
                        @saveDataFn="saveDataFn"
                        @submitDataFn="submitDataFn"
                        @printPermit="printPermit"
                        @childBusinessForm="childBusinessForm"
                        @closeSpin="closeSpin"
                        @setProgram = "setProgram"
                        @baseInfo="setBaseInfo"
                    />
                </div>
            </Panel>
            <Panel name="6" v-if="(isApprove && !isReadOnly) || this.pageParams.processStatus==='approved'">
                当前用户: {{userInfo ? userInfo.userRealName :''}}
                <div class="content" slot="content">
                    <ContractCurrentUser ref="contractCurrentUser" :Obj="Obj" :approveType="approveType"
                                         @childUserForm="childUserForm" @closeSpin="closeSpin"/>
                </div>
            </Panel>
        </Collapse>
        </div>
    </Card>
</template>
<script>
    import moment from "moment";

    import {
        bankCardApprove,
        changeContractBankCardInfo,
        downloadBatchFile,
        printPermitFile,
        submitBankManage,
        mergeUploadFile
    } from "_p/basic/api/contract/post-loan-info-change";
    // 日志
    import approveHistory from "_p/basic/pages/contract/common/approve-history/approve-history";
    // 金融产品
    import FinanceInfo from "_p/basic/pages/contract/common/finance-info/finance-info";
    // 业务办理
    import Business from "_p/basic/pages/contract/post-loan-info-change/change-bank-card-detial/Business";
    // 合同信息
    import contractInfo from "_p/basic/pages/contract/common/contract-info/contract-info";
    // 基本信息
    import BaseInfo from "_p/basic/pages/contract/common/base-info";
    // 当前用户
    import ContractCurrentUser from "_p/basic/pages/contract/common/current-user/contractCurrentUser";
    //附件校验
    import {checkFile,} from "_p/basic/api/image/image-upload";

    export default {
        components: {
            approveHistory,
            FinanceInfo,
            contractInfo,
            BaseInfo,
            Business,
            ContractCurrentUser
        },
        props: {
            Obj: {
                //caseNo, contractNo, roleType
                type: Object,
                required: true
            },
            spinShow: {
                type: Boolean,
                required: true
            },
            // 是否是供应商
            isSP: {
                type: Boolean,
                required: true
            },
            //是否是审批页面
            isApprove: {
                type: Boolean,
                required: true
            },
            //是否 审批完成
            isApproved: {
                type: Boolean,
                required: true
            },
            isReadOnly: {
                type: Boolean,
                default: false
            },
            pageParams: {
                type: Object,
                required: true
            },
            //合同号
            contractNo: {
                type: String,
                required: true
            },
            dataDict: {
                type: Object
            },
            userInfo: {
                type: Object,
                required: true
            },
            businessSource: {
                type: String,
                required: true
            },
            roleType: {
                type: Array,
                required: true
            }
            // @showSpin="showSpin"
            // @closeSpin="closeSpin"
            // @back="back"
        },
        data() {
            return {
                approveType: null,
                fileList: [],
                indeterminate: false,
                checkAll: false,
                checkAllGroup: [],
                uploadFile: {
                    busiType: "",
                    busiNo: "",
                    busiData: {}
                },
                bankCardManageVOs: [],
                templateList: {},

                openPanel: [ 2, 3, 4, 5, 6],
                readOnly: null,
                loading: true,
                approvalOperating: "", //审批结果
                pageInfo: this.pageParams
            };
        },

        mounted() {
            this.init();
        },
        methods: {
            init() {
                if (this.$refs.baseInfo) {
                    this.$refs.baseInfo.formData = Object.assign(
                        {},
                        this.$refs.baseInfo.formData,
                        this.pageInfo
                    );
                }
            },
            save() {
                if (this.$refs.business) {
                    this.showSpin();
                    // this.saveDataFn();
                    this.$refs.business.formValidate("saveDataFn");
                }
            },

            submit() {
                this.$Modal.confirm({
                    title: "确认提交？",
                    onOk: () => {
                        if (this.$refs.business) {
                            this.showSpin();
                            this.$refs.business.formValidate("submitDataFn");
                        }
                    }
                });
            },

            //客户打印模板
            printFile() {
                if (this.$refs.business) {
                    this.showSpin();
                    this.$refs.business.formValidate("printPermit");
                }
            },
            setSmallprogram() {
                if (this.$refs.business) {
                    this.showSpin();
                    this.$refs.business.formValidate("setProgram");
                }
            },
            // 审核等按钮
            approve(name) {
                if (!name) return;
                let t, val;
                switch (name) {
                    case "pass":
                        t = "审核通过";
                        val = "suggestCheckF";
                        break;
                    /*case "return":
                        t = "退件";
                        val = "sendBack";
                        break;*/
                    case "reject":
                        t = "拒绝";
                        val = "suggestRejectF";
                        break;
                }
                this.approveType = name;
                this.$Modal.confirm({
                    title: `确认${t}？`,
                    onOk: () => {
                        if (this.$refs.business) {
                            this.showSpin();
                            this.approvalOperating = val;
                            // 验证 business 组件数据 给下一个方法
                            this.$refs.business.formValidate("childBusinessForm");
                        }
                    }
                });
            },
            // 保存 请求
            saveDataFn(data) {
                if (!data) return;
                let d = this.formatData(data);
                console.log("保存参数",d)
                if (d.isLongTerm == true){
                    d.certEndDate ="9999-12-31"
                    console.log(d.certEndDate,"1111222")
                }
                changeContractBankCardInfo(d)
                    .then(res => {
                        this.$emit("closeSpin");
                        if (res.code === "0000") {
                            this.$Message.success("保存成功!");
                            // if (this.pageInfo.caseNo)
                            this.pageInfo = res.data;
                            console.log("this.pageinfo", this.pageInfo)
                            // this.$refs.baseInfo.formData = res.data;
                        }
                    })
                    .catch(e => {
                        this.$emit("closeSpin");
                    });
            },
            //生成二维码
            setProgram(data){
                let d = this.formatData(data);
                changeContractBankCardInfo(d)
                    .then(res => {
                        this.$emit("closeSpin");
                        if (res.code === "0000") {
                            // if (this.pageInfo.caseNo)
                            this.pageInfo = res.data;
                            // this.$refs.baseInfo.formData = res.data;
                            //保存数据，生成二维码

                            printPermitFile(res.data)
                                .then(res => {
                                    this.$emit("closeSpin");
                                    if (res.code === "0000") {
                                        //生成二维码后，生成上传文件
                                        console.log("chufa",res)
                                    }
                                })
                            //合成文件
                            mergeUploadFile(res.data);
                            //生成二维码
                            this.$refs.business.refresh(res.data);
                        }
                    })
                    .catch(e => {
                        this.$emit("closeSpin");
                    });
            },
            //影像件校验
            checkFile(v) {
                this.uploadFile.busiNo = v.caseNo;
                this.uploadFile.busiType = 'bankCard';
                if (!checkFile(this.uploadFile)) return;
                checkFile(this.uploadFile).then(res => {
                    if (res.code === "0000") {
                        console.log("校验后，提交前数据", data)
                        this.submitPageData(data);
                        return true;
                    }
                }).catch(e => {
                    this.$emit("closeSpin");
                });
            },
            //客户页面打印模板
            printPermit(data) {
                this.save();
                data.smallprogram = "yes";
                printPermitFile(data)
                    .then(res => {
                        this.$emit("closeSpin");
                        if (res.code === "0000") {
                            //打印完自动关闭页面
                            // this.back();
                            console.log("chufa",res)
                            this.downBatchFile(res.data);
                        }
                    })
                    .catch(e => {
                        this.$emit("closeSpin");
                    });
            },
            downBatchFile(v) {
                let params = {
                    attachmentList: v,
                }
                console.log(params, "调用的参数集合")
                let self = this
                downloadBatchFile(v).then(function (response) {
                    if (response.status === 200) {
                        self.afs.downloadFile(response);
                        this.$Message.success("下载完成")
                    }
                })
            },

//提交 请求
            submitDataFn(data) {
                console.log("提交参数",data)
                let d = this.formatData(data);
                data.department =  d.department;
                submitBankManage(data)
                    .then(res => {
                        this.$emit("closeSpin");
                        if (res.code === "0000") {
                            this.$Message.success("提交成功!");
                            this.back();
                        }
                    })
                    .catch(e => {
                        this.$emit("closeSpin");
                    });
                this.init();
            },
            // let d = this.formatData(data);
            // console.log("参数",d)
            // this.uploadFile.busiNo = d.caseNo;
            // this.uploadFile.busiType = 'bankCard';
            // if(!checkFile(this.uploadFile)) return;
            // checkFile(this.uploadFile).then(res => {
            //     if (res.code === "0000") {
            //       console.log("校验后，提交前数据",data)

            //       console.log("提交前的数据",data);
            //       if (!data) return;
            //       data.approvalOperating = "suggestCheckF"
            //       let d = this.formatData(data);
            //       console.log("提交前的数据",data)
            //     }
            //   }).catch(e => {
            //     this.$emit("closeSpin");
            //   });

            // 审批 请求
            // Business 组件数据
            childBusinessForm(data) {
                if (!data) return;
                // let bussiness = this.formatData(data);
                // 验证 contractCurrentUser 组件数据 传给下个方法
                this.$refs.contractCurrentUser.formValidate(
                    "childUserForm",
                    this.formatData(data),
                    this.approveType
                );
            },
            // contractCurrentUser 组件数据
            childUserForm(data) {
                if (!data) return;
                this.bankCardManageVOs.push(data);
                // let d = Object.assign({}, this.bankVOs, {
                //     approvalOperating: this.approvalOperating,
                //     bankCardManageVOs: this.bankVOs
                // });
                let d = {
                    approvalOperating: this.approvalOperating
                    , bankCardManageVOs: this.bankCardManageVOs,
                    approvalOpinion: data.approvalOpinion
                }
                console.log("审批前的数据", d)
                console.log("审批前数据data", data)
                bankCardApprove(d)
                    .then(res => {
                        this.$emit("closeSpin");
                        if (res.code === "0000") {
                            this.$Message.success("成功!");
                            this.back();
                        }
                    })
                    .catch(e => {
                        this.$emit("closeSpin");
                    });
            },

            // 格式化
            formatData(data) {
                if (!data) return {};
                let d = Object.assign({businessSource: this.businessSource}, this.pageInfo, data);
                if (this.isSP) {
                    d.department = d.channelFullName;
                } else {
                    d.department = this.userInfo.userRealName;
                }
                console.log("d.partment",d)
                if (d.createTime instanceof Date)
                    d.createTime = moment(d.createTime).format(
                        "YYYY-MM-DD HH:mm:ss"
                    );
                if (d.endDate instanceof Date)
                    d.endDate = moment(d.endDate).format("YYYY-MM-DD HH:mm:ss");
                return d;
            },
            showSpin() {
                this.$emit("showSpin");
            },
            closeSpin() {
                this.$emit("closeSpin");
            },
            back() {
                this.$emit("back");
            },

            //获取点选数据
            getAttachmentData(v) {
                console.log("点选获取的值:", v);
            },
            handleCheckAll() {
                if (this.indeterminate) {
                    this.checkAll = false;
                } else {
                    this.checkAll = !this.checkAll;
                }
                this.indeterminate = false;
                if (this.checkAll) {
                    let codeList = this.fileList.map((item, index) => {
                        return item.attachmentCode;
                    })
                    this.checkAllGroup = codeList;
                } else {
                    this.checkAllGroup = [];
                }
            },
            checkAllGroupChange(data) {
                if (data.length === this.fileList.length) {
                    this.indeterminate = false;
                    this.checkAll = true;
                } else if (data.length > 0) {
                    this.indeterminate = true;
                    this.checkAll = false;
                } else {
                    this.indeterminate = false;
                    this.checkAll = false;
                }
            },
            setBaseInfo(data) {
                const {caseNo, applyBy, applyDate} = data;
                console.log("基础信息的data",data)
                let obj = {
                    caseNo:this.pageInfo.caseNo || caseNo,
                    applyBy: this.pageInfo.applyBy || applyBy,
                    applyDate: this.pageInfo.applyDate || applyDate
                }
                this.pageInfo = Object.assign({}, this.pageInfo, obj)
            },

        }
    };
</script>
